package com.ruoyi.jihuo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author：LXY
 * @DATE：2025-08-20 13:47
 * @Description：异步任务线程池配置
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig {
    /**
     * 上传数据包专用线程
     * @return 配置好的线程池执行器
     */
    @Bean("uploadDataAnalysisExecutor")
    public ThreadPoolTaskExecutor uploadDataAnalysisExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 队列大小
        executor.setQueueCapacity(50);
        // 线程名前缀
        executor.setThreadNamePrefix("UploadData-Analysis-");
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        // 优雅关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);

        // 拒绝策略 - 使用自定义拒绝策略，添加日志记录
        executor.setRejectedExecutionHandler(new LoggingCallerRunsPolicy("uploadDataAnalysisExecutor"));

        executor.initialize();
        return executor;
    }
    
    /**
     * 发布天猫任务专用线程
     * @return 配置好的线程池执行器
     */
    @Bean("releaseATaskAnalysisExecutor")
    public ThreadPoolTaskExecutor releaseATaskAnalysisExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数
        executor.setCorePoolSize(3);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列大小
        executor.setQueueCapacity(30);
        // 线程名前缀
        executor.setThreadNamePrefix("releaseATask-Analysis-");
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        // 优雅关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);

        // 拒绝策略 - 使用自定义拒绝策略，添加日志记录
        executor.setRejectedExecutionHandler(new LoggingCallerRunsPolicy("releaseATaskAnalysisExecutor"));

        executor.initialize();
        return executor;
    }
    
    /**
     * 自定义拒绝策略，在触发拒绝时记录日志信息
     */
    private static class LoggingCallerRunsPolicy implements RejectedExecutionHandler {
        private final String executorName;
        
        public LoggingCallerRunsPolicy(String executorName) {
            this.executorName = executorName;
        }
        
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            // 记录拒绝策略触发的日志信息
            log.warn("线程池[{}]触发拒绝策略: 队列大小={}, 活跃线程数={}, 已完成任务数={}, 总任务数={}",
                    executorName,
                    e.getQueue().size(),
                    e.getActiveCount(),
                    e.getCompletedTaskCount(),
                    e.getTaskCount());
            
            // 使用调用者运行策略执行任务
            if (!e.isShutdown()) {
                log.info("使用调用者线程执行被拒绝的任务");
                r.run();
            }
        }
    }
}
